#include "log.hpp"
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        cout<<"应该输入2个参数 : "<<argv[0]<<" ip port "<<endl;
        exit(1);
    }
    //创建套接字
    int sock = socket(AF_INET,SOCK_DGRAM,0);
    if(sock < 0)
    {
        logMassage(FATAL,"%d: %s\n",errno,strerror(errno));
        exit(2);
    }
    struct sockaddr_in severinfo;
    memset(&severinfo,0,sizeof severinfo);
    severinfo.sin_family = AF_INET; 
    //severinfo.sin_addr.s_addr = inet_addr(argv[1]);
    severinfo.sin_port = htons(atoi(argv[1]));
    char* buffer[1024];
    string massage;
    while(1)//循环式接收数据
    {
        cout<<"请输入信息：";
        getline(cin,massage);
        if(massage == "quit") break;
        sendto(sock,massage.c_str(),massage.size(),0,(struct sockaddr*)&severinfo,sizeof severinfo);
        struct sockaddr_in tem;
        memset(&tem,0,sizeof tem);
        socklen_t temlen = sizeof tem;
        ssize_t sizeofrecv = recvfrom(sock,buffer,sizeof buffer - 1,0,(struct sockaddr*)&tem,&temlen);
        if(sizeofrecv < 0)
        {
            logMassage(FATAL,"%d: %s\n",errno,strerror(errno));
            exit(4);
        }
        else
        {
            buffer[sizeofrecv] = 0;
            printf("%s\n",buffer);
        }
    }
    close(sock);
    return 0;
}